package team.you.change.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.you.change.dao.TableMapper;
import team.you.change.util.Result;
import team.you.change.pojo.Table;
import team.you.change.service.TableService;
import team.you.change.util.YuoUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TableServiceImpl implements TableService {
    @Autowired
    private TableMapper tableMapper;
    //课程名，教师名，教室代码，班级代码，学年，学期，周数，时间范围，当前页码，每页条数
    @Override
    public Result getAllTables(String courseName, String realName, String roomCode, String classCode,Integer year,Integer term,
                               Integer week, String time, Integer page, Integer limit) {
        Result result = new Result();
        String sTime = ""; //开始时间
        String eTime = ""; //结束时间
        if(time != null){
            String[] times = time.trim().split("~"); //对时间字符串进行去空格和分割处理
            sTime = times[0];
            eTime = times[1];
        }
        String year0 = "";
        switch (year.intValue()){  //根据学年标识，获取学年字符串
            case 0: year0 = "2020-2021";break;
            case 1: year0 = "2019-2020";break;
            case 2: year0 = "2021-2022";break;
            case 3: year0 = "2022-2023";break;
            default:break;
        }
        //调用数据接口
        List<Table> tables = tableMapper.selectAll(courseName, realName, roomCode, classCode, year0, term, week, sTime, eTime,
                YuoUtil.getPage(page, limit), limit);
        Integer count = tableMapper.getCount(courseName, realName, roomCode, classCode, year0, term, week, sTime, eTime);
        //设置数据并返回
        return YuoUtil.setData(result, tables, count);
    }

    @Override
    public Result del(Integer id) {
        Result result = new Result();
        Table table = tableMapper.selectByPrimaryKey(id);
        if (table != null) {
            try {
                return YuoUtil.crudMsg(tableMapper.deleteByPrimaryKey(id), result);
            }catch (Exception e){
                return YuoUtil.setErrorMsg(e, result);
            }
        } else {
            result.setCode(500);
            result.setMsg("该行不存在");
        }
        return result;
    }

    @Override
    @Transactional
    public Result delete(Integer[] ids) {
        Result result = new Result();
        try {
            for (int i = 0; i < ids.length; i++) {
                tableMapper.deleteByPrimaryKey(ids[i]);
            }
            return result;
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result update(Integer id, String value, String field) {
        Result result = new Result();
        try {
            return YuoUtil.crudMsg(tableMapper.UpdateByKey(id, value, field), result);
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result getChangeTables(String courseName, String realName, String roomCode, String classCode,String year, Integer term,
                                  Date time, Integer page, Integer limit) {
        Result result = new Result();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sTime = "";
        String eTime = "";
        if(time != null){
            Calendar cal = Calendar.getInstance();
            Calendar cal1 = Calendar.getInstance();
            cal.setTime(time);
            cal1.setTime(time);
            cal.add(Calendar.DAY_OF_MONTH, 1);
            cal1.add(Calendar.DAY_OF_MONTH, 14);
            sTime = sdf.format(cal.getTime());
            eTime = sdf.format(cal1.getTime());
        }
        List<Table> tables = tableMapper.selectAll(courseName, realName, roomCode, classCode, year, term,0, sTime, eTime,page,limit);
        return YuoUtil.setData(result, tables, tables.size());
    }

    @Override
    public Result add(String userId, String classId, String roomId, String courseId, String createTime, Integer timeSlot) {
        Result result = new Result();
        Table table = new Table();
        table.setUserId(userId);
        table.setClassId(classId);
        table.setRoomId(roomId);
        table.setCourseId(courseId);
        //将字符串转换为时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = null;
        try {
             time = sdf.parse(createTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        table.setCreateTime(time);
        table.setTimeSlot(timeSlot);
        //处理时间 获取周数和周几 学年、学期
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        int year = cal.get(Calendar.YEAR) % 100;
        int month = cal.get(Calendar.MONTH) + 1;
        if(month > 6) year++;
        StringBuilder shcoolYear = new StringBuilder("20");
        shcoolYear.append((year - 1) + "-");
        shcoolYear.append("20" + year);
        table.setSchoolYear(shcoolYear.toString());
        table.setSchoolTerm(month > 6 ? 1 : 2);
        table.setWeek(cal.get(Calendar.WEEK_OF_YEAR) - 1);
        table.setWeekNum(cal.get(Calendar.DAY_OF_WEEK) - 1);
        table.setState(0);
        try {
            //判断课程是否冲突
            if(checkTable(table)){
                return YuoUtil.crudMsg(tableMapper.insert(table), result);
            }else {
                result.setCode(500);
                result.setMsg("课程冲突");
                return result;
            }
        }catch (Exception e){
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result selectSlot(String time, Table table) {
        Result result = new Result();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(time);
            table.setCreateTime(date);
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i <= 5; i++){ //获取不冲突的节数
                table.setTimeSlot(i);
                if (checkTable(table)){
                    list.add(i);
                }
            }
            result.setData(list);
            return result;
        } catch (ParseException e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    /**
     * 检查课程是否冲突
     * @param table 新增课表信息
     * @return 是否冲突
     */
    public boolean checkTable(Table table){
        List<Table> tables = tableMapper.selectByTime(table.getCreateTime(), table.getTimeSlot());
        if (tables.size() > 0){
            Iterator<Table> iterator = tables.iterator();
            while (iterator.hasNext()){
                Table next = iterator.next();
                if(table.getUserId().equals(next.getUserId()) && table.getCourseId().equals(next.getCourseId())
                && table.getRoomId().equals(next.getRoomId()) && table.getClassId().equals(next.getClassId())){
                    return false;
                }else {
                    return true;
                }
            }
        }
        return false;
    }
}
